package com.ygo.feihua;

import android.app.*;
import android.content.*;
import android.net.*;
import android.os.*;
import android.view.*;
import android.view.View.*;
import android.widget.*;
import android.widget.Gallery.*;
import java.io.*;

import android.view.View.OnClickListener;
import java.lang.Process;
import android.graphics.*;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import cn.bmob.v3.BmobQuery;
import com.ygo.feihua.BmobTable.GxWz;
import cn.bmob.v3.listener.FindListener;
import java.util.List;
import cn.bmob.v3.exception.BmobException;
import com.ygo.feihua.util.*;
import com.ygo.feihua.Management.*;

public class NewKatuxiazai extends AppCompatActivity 
{
	
	Dialog builder;
    TextView xkt_sm;
	long jd=0;
	Button update_integration,update_single,update_decompression,xkt_kabiao,update_download_ygo;
	EditText xkt_km;
	AlertDialog dialog;
	Boolean bb=false;
	String[] kzl;//listview的显示条目的数据数组
	Context context=NewKatuxiazai.this;
	Gongju gj;
	DialogUtils du;
    TextView t1;

	
	Handler handler=new Handler(){
		public void handleMessage(final Message msg)
		{
			switch (msg.what)
			{
				case 1:
					Toast.makeText(getApplicationContext(), msg.obj.toString(), 0).show();
					return;
				case 2:
                    t1.setText(msg.obj.toString() + "\n");
					return;
				case 3:
					finish();
					return;
				case 4:
					gj.show("替换成功");
				du.dis();
					return;
				case 5:
                    View[] v3=du.dialogt(false,"","卡表替换失败,是否分析原因？");
                    Button b1=(Button) v3[0];
                    Button b2=(Button) v3[1];
                    b1.setText("是");
                    b2.setText("否");
                    b2.setOnClickListener(new OnClickListener(){

                            @Override
                            public void onClick(View p1)
                            {
                                du.dis();
                                // TODO: Implement this method
                            }
                        });
                    b1.setOnClickListener(new OnClickListener(){

                            @Override
                            public void onClick(View p1)
                            {
                                
                                du.dis();
                                du.dialogj1(false,"","正在分析原因,请稍等");
								String[] ss={gj.PATH_GEN,
											gj.PATH_GEN+"core/",
											gj.PATH_GEN+"core/3.5/",
											gj.PATH_GEN+"core/3.5/cofig/",
											gj.PATH_GEN+"core/3.5/cofig/lflist.conf"};
							   for(int i=0;i<ss.length;i++){
								   
								   if(!new File(ss[i]).isDirectory()){
									   du.dis();
									   gj.show(ss[i]+"目录不存在");
									   return;
								   }else{
									   if(!new File(ss[i]).canWrite()){
										   du.dis();
										   gj.show(ss[i]+"没有写入权限");
										   return;
									   }
								   }
							   }
                                   
                                du.dis();
                                gj.show("未知原因,错误为"+msg.obj.toString());
                                // TODO: Implement this method
                            }
                        });
                    
					return;
				case 6:
					gj.show("未知错误");
					return;
				case 7:
					gj.show("请确定你选择的文件是lflist.conf或者目录中没有lflist.conf文件");
					return;
                case 8:
                    View[] v=du.dialogj1(false,"","解压准备中");
                    t1= (TextView) v[0];
                    return;
                 case 9:
                     du.dis();
                     return;
				case 10:
					View[] v5=du.dialogt(false,"","卡表替换失败,是否分析原因？");
                    Button b51=(Button) v5[0];
                    Button b52=(Button) v5[1];
                    b51.setText("是");
                    b52.setText("否");
                    b52.setOnClickListener(new OnClickListener(){

                            @Override
                            public void onClick(View p1)
                            {
                                du.dis();
                                // TODO: Implement this method
                            }
                        });
                    b51.setOnClickListener(new OnClickListener(){

                            @Override
                            public void onClick(View p1)
                            {

                                du.dis();
								String ygopa=SharedPreferenceUtil.getYgopath();
                                du.dialogj1(false,"","正在分析原因,请稍等");
								String[] ss={
									
									Gongju.PATH_GEN,
									ygopa,
									ygopa+"lflist.conf"};
								for(int i=0;i<ss.length;i++){

									if(!new File(ss[i]).isDirectory()){
										du.dis();
										gj.show(ss[i]+"目录不存在");
										return;
									}else{
										if(!new File(ss[i]).canWrite()){
											du.dis();
											gj.show(ss[i]+"没有写入权限");
											return;
										}
									}
								}

                                du.dis();
                                gj.show("未知原因,错误为"+msg.obj.toString());
                                // TODO: Implement this method
                            }
                        });

					return;
					
				case 11:
					du.dis();
					gj.show("解压成功");
					Intent in=IntentUtil.getApkFileIntent(NewKatuxiazai.this,msg.obj.toString());
					if(in!=null){
						startActivity(in);
					}
					return;
			}

		};
	};
	

	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO: Implement this method
		super.onCreate(savedInstanceState);
		setContentView(R.layout.katuxiazai);
		
		SdkInitManagement.getDx().initBmobSdk();
		
		gj=Gongju.getdx(this);
		du=DialogUtils.getdx(this);
		gj.cshToolbar((Toolbar) findViewById(R.id.toolbar),"返回");
		
		update_integration = (Button) findViewById(R.id.update_integration);
		update_single = (Button) findViewById(R.id.update_single);
		update_decompression = (Button) findViewById(R.id.update_decompression);
		xkt_kabiao=(Button) findViewById(R.id.xkt_kabiao);
		xkt_sm=(TextView) findViewById(R.id.xkt_sm);
        update_download_ygo=(Button) findViewById(R.id.update_download_ygo);
		
		
		Intent intent =this. getIntent();
		String action = intent.getAction();
		if(intent.ACTION_VIEW.equals(action)){
			Uri uu= intent.getData();
			if(uu!=null){
			String path1=uu.getPath();//intent.getData().getPath()为打开文件的绝对路径
			new DecompressionZipThread(path1, gj.getJypath(path1), handler);
			}
		}else{
			
			SharedPreferences setting=getSharedPreferences("kaiguan",MODE_PRIVATE);  //PreferenceManager.getDefaultSharedPreferences(this);
			boolean str = setting.getBoolean("zygx",true);//.getString("key","no");
			if(str){
				View[] v= du.dialogt1(false,"","如果是第一次更新:\n第一步:完整包\n第二步:点选择数据包解压选择你下载好的资源包\n第三步:打开ygomobile的设置-游戏设置,点自定义数据库选择cdb文件\n\n如果要更新某个卡包,点每次的更新包下载你想更新的包后,剩下的步骤参照第二步和第三步即可");
				Button b1=(Button) v[0];
				b1.setText("确定");
				b1.setOnClickListener(new OnClickListener(){

						@Override
						public void onClick(View p1)
						{
							du.dis();
							// TODO: Implement this method
						}
					});
			}
		}
		xkt_sm.setOnClickListener(new OnClickListener(){

                @Override
                public void onClick(View p1)
                {
                   View[] v= du.dialogt1(false,"","如果是第一次更新:\n第一步:完整包\n第二步:点选择数据包解压选择你下载好的资源包\n第三步:打开ygomobile的设置-游戏设置,点自定义数据库选择cdb文件\n\n如果要更新某个卡包,点每次的更新包下载你想更新的包后,剩下的步骤参照第二步和第三步即可");
                   Button b1=(Button) v[0];
                   b1.setText("确定");
                    b1.setOnClickListener(new OnClickListener(){

                            @Override
                            public void onClick(View p1)
                            {
                                du.dis();
                                // TODO: Implement this method
                            }
                        });
                    // TODO: Implement this method
                }
            });
		update_download_ygo.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View p1)
				{
					du.dialogDygo();
					
					
					// TODO: Implement this method
				}
			});
		
		xkt_kabiao.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View p1)
				{
					View[] vv1=du.dialogt(false,"","替换卡表前请确认ygomobile已关闭,否则会导致出现奇怪的bug\n直接替换2018.1.1 OCG禁卡表或是选择卡表替换?");
					Button bb1=(Button) vv1[0];
					Button bb2=(Button) vv1[1];
					bb1.setText("直接替换");
					bb2.setText("选择替换");
					bb1.setOnClickListener(new OnClickListener(){

							@Override
							public void onClick(View p1)
							{

								new th1().start();
								// TODO: Implement this method
							}
						});
					bb2.setOnClickListener(new OnClickListener(){

							@Override
							public void onClick(View p1)
							{
								Intent intent=new Intent();
								intent.putExtra("lx",NewWjxz.TYPE_LIFLIST);
								intent.putExtra("path",Gongju.PATH_GEN);
								intent.setClass(NewKatuxiazai.this,NewWjxz.class);
								startActivityForResult(intent,2);

								// TODO: Implement this method
							}
						});
					// TODO: Implement this method
				}
			});
		

		update_integration.setOnClickListener(new OnClickListener(){
				public void onClick(View p1)
				{
					BmobQuery<GxWz> bq=new BmobQuery<GxWz>();
					bq.addWhereEqualTo("name","整合包");
					bq.findObjects(new FindListener<GxWz>(){

							@Override
							public void done(List<GxWz> p1, BmobException p2)
							{
								if(p2==null){
								String wz=p1.get(0).getWz();
									startActivity(IntentUtil.getUrlIntent(NewKatuxiazai.this,wz));
								
								}else{
									gj.show("查询错误"+p2.getMessage());
								}
								// TODO: Implement this method
							}

						});
					
					
				}
			});
		update_single.setOnClickListener(new OnClickListener(){
				public void onClick(View p1)
				{
					BmobQuery<GxWz> bq=new BmobQuery<GxWz>();
					bq.addWhereEqualTo("name","每次包");
					bq.findObjects(new FindListener<GxWz>(){

							@Override
							public void done(List<GxWz> p1, BmobException p2)
							{
								if(p2==null){
									String wz=p1.get(0).getWz();
									startActivity(IntentUtil.getUrlIntent(NewKatuxiazai.this,wz));
									
								}else{
									gj.show("查询错误"+p2.getMessage());
								}
								// TODO: Implement this method
							}
						});				
				}
			});
		update_decompression.setOnClickListener(new OnClickListener(){
				public void onClick(View p1)
				{
					Intent intent=new Intent();
					
					intent.putExtra("lx",NewWjxz.TYPE_ZIP);
					intent.putExtra("path",Gongju.PATH_GEN);
					intent.setClass(NewKatuxiazai.this,NewWjxz.class);
					startActivityForResult(intent,0);
				}
			});
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// TODO: Implement this method

		getMenuInflater().inflate(R.menu.menu_wq, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		// TODO: Implement this method
		switch(item.getItemId()){
			case R.id.action_wq:
				startActivity(new Intent(NewKatuxiazai.this,GengxinWangqi.class));

				break;
		}


		return super.onOptionsItemSelected(item);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		// TODO: Implement this method
		super.onActivityResult(requestCode, resultCode, data);
		switch(requestCode){
			case 0:
		String result = data.getStringExtra("path");
		if(!result.equals("")){
		new DecompressionZipThread(result, gj.getJypath(result), handler);
		}
		
		break;
	
		case 2:
				final String kbb=data.getStringExtra("path");
				if (!kbb.equals(""))
				{
					new Thread(new Runnable(){

							@Override
							public void run()
							{
								String fileName = "lflist.conf";
								String[] kb1=kbb.split("/");
								String kb2=kb1[kb1.length - 1];
								if (kb2.equals(fileName))
								{
									ydkb1(kbb);
								}
								else
								{
									if (FileUtil.cmm(kbb, fileName))
									{
										String kb3="";
										for (int i=0;i < kb1.length - 1;i++)
										{
											kb3 = kb1[i] + "/";
										}
										if (kb3.equals(""))
										{
											Message m=new Message();
											m.what = 6;
											handler.sendMessage(m);

										}
										else
										{
											ydkb1(kb3 + fileName);
										}
									}
									else
									{
										Message m=new Message();
										m.what = 7;
										handler.sendMessage(m);
									}
								}
								// TODO: Implement this method
							}
						}).start();
					
					}
			break;
			
		}
	}
	
	public void ydkb1(String path){
		try
		{
			String fileName = "lflist.conf";
			//拿到输入流
			InputStream in = new FileInputStream(path);
			//打开输出流
			FileOutputStream out = new FileOutputStream(SharedPreferenceUtil.getYgopath()+"core/3.5/config/"+fileName);
			int len = -1 ;
			byte[] bytes = new byte[1024];
			//不断读取输入流
			while ((len = in.read(bytes)) != -1)
			{
				//写到输出流中
				out.write(bytes, 0, len);
			}
			out.close();
			in.close();

			Message m=new Message();
			m.what = 4;
			handler.sendMessage(m);
		}
		catch (IOException e)
		{
			Message m=new Message();
			m.what = 10;
			handler.sendMessage(m);
		}
	}
	
	
	
	
	class th1 extends Thread
	{

		@Override
		public void run()
		{
			// TODO: Implement this method
			super.run();	

			try
			{
				gj.copyAssets("lflist.conf", SharedPreferenceUtil.getYgopath());
				handler.sendEmptyMessage(4);
			}catch (IOException e){
				Message m=new Message();
				m.what = 10;
				m.obj=""+e;
				handler.sendMessage(m);
			}

		}
	}
}
